import React from 'react';
import { Select } from 'antd';
import { axhelper } from '@/shared/axhelper';

const { Option } = Select;
/**
 * 自定义搜索下拉框
 * @param label 标签
 * @param field 字段名称
 * @param enumName 枚举类型
 * @param mode 模式 'multiple' | 'tags' | '-'
 * @param placeholder 占位符
 */
export class AxSelectEnum extends React.Component {
  handleChange = val => {
    const { onChange } = this.props;
    if (onChange) {
      onChange(val);
    }
  };

  render() {
    const { enumName } = this.props;
    const data = axhelper.getDicByEnumName(enumName);

    return (
      <Select
        showSearch
        field={this.props.field}
        style={{ width: '100%' }}
        mode={this.props.mode ? this.props.mode : '-'}
        placeholder={this.props.placeholder ? this.props.placeholder : `请选择${this.props.label}`}
        filterOption={(input, option) =>
          option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
        }
        onChange={this.handleChange}
      >
        {data.map((d, idx) => (
          <Option key={idx} value={d.value}>
            {d.text}
          </Option>
        ))}
      </Select>
    );
  }
}

/**
 * 自定义搜索下拉框（简单查询）
 * @param label 标签
 * @param field 字段名称
 * @param enumName 枚举类型
 * @param axvalue 默认值
 * @param mode 模式 'multiple' | 'tags' | '-'
 * @param placeholder 占位符
 */
export class AxSelectEnumForSimple extends React.Component {
  constructor(props) {
    super(props);
    const value = props.axvalue;

    this.state = {
      value,
      axvalue: value,
    };
  }

  componentWillReceiveProps(newProps) {
    const { axvalue } = newProps;
    const { axvalue: preAxvalue } = this.state;

    // 这段代码可能看起来非常混乱，这个props可以被当做缓存，仅用作判断
    if (axvalue !== preAxvalue) {
      const { onChange } = this.props;
      this.setState({
        value: axvalue,
        axvalue,
      });
      if (onChange) {
        onChange(axvalue);
      }
    }
  }

  handleChange = val => {
    const { onChange } = this.props;
    this.setState({
      value: val,
    });
    if (onChange) {
      onChange(val);
    }
  };

  render() {
    const { value } = this.state;
    const { enumName, ...rest } = this.props;
    const data = axhelper.getDicByEnumName(enumName);

    return (
      <Select
        showSearch
        size={window.ax.config.size}
        field={this.props.field}
        style={{ width: '100%' }}
        mode={this.props.mode ? this.props.mode : '-'}
        placeholder={this.props.placeholder ? this.props.placeholder : `请选择${this.props.label}`}
        filterOption={(input, option) =>
          option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
        }
        value={value}
        onChange={this.handleChange}
        {...rest}
      >
        {data.map(d => (
          <Option key={d.value} value={d.value}>
            {d.text}
          </Option>
        ))}
      </Select>
    );
  }
}
